import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:gameplay_flutter/lib_baseview/theme/jr.dart';
import 'package:gameplay_flutter/m_discover/player/player_view.dart';
import 'package:get/get.dart';
import 'package:ones/ui.dart';

import '../../generated/assets.dart';
import '../../lib_basemodel/discover/moment_entity.dart';
import '../../lib_baseview/lib_baseview.dart';
import '../../lib_im/index.dart';
import '../../m_me/user_details_page/user_details_page.dart';
import '../../resource/language/generated/l10n.dart';
import '../post/post_view.dart';
import '../post_detail/post_detail_view.dart';
import 'discover_home_logic.dart';

class DiscoverHomePage extends StatelessWidget {
  DiscoverHomePage({Key? key}) : super(key: key);
  final DiscoverHomeLogic logic = Get.put(DiscoverHomeLogic());

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      return Scaffold(
        backgroundColor: Color(0xffFBFBFB),
        body: Stack(
          children: [
            Container(height: 132).linearGradientColor([Color(0xffDCD4FF), Color(0xffFBFBFB)],
                begin: Alignment.topCenter, end: Alignment.bottomCenter),
            SafeArea(
              child: DefaultTabController(
                length: 2,
                child: Column(
                  children: [
                    Row(
                      children: [
                        TabBar(
                          tabAlignment: TabAlignment.start,
                          padding: EdgeInsets.zero,
                          dividerColor: Colors.transparent,
                          isScrollable: true,
                          indicator: UnderlineTabIndicator(
                            borderRadius: BorderRadius.circular(100),
                            borderSide: const BorderSide(width: 3.5, color: Color(0xFF8673F6)),
                          ),
                          indicatorPadding: EdgeInsets.symmetric(horizontal: 10),
                          indicatorColor: Color(0xff8A72FE),
                          labelStyle: TextStyle(color: Color(0xff1B1B1B), fontSize: 22, fontWeight: FontWeight.w600),
                          unselectedLabelStyle: TextStyle(color: Color(0xffA397DE), fontSize: 18),
                          tabs: [
                            Tab(text: T.current.discover1_explore),
                            Tab(text: T.current.discover2_following),
                          ],
                        ),
                        Spacer(),
                        Image.asset(Assets.discoverEdit, width: 28, height: 28).onClick(() async {
                          var res = await Get.to(() => PostPage());
                          // if (res == true) {
                          //   logic.discoverProductFlow();
                          //   logic.discoverFollowingDynamicList();
                          // }
                          if (res is int) {
                            // logic.moments.insert(0, res);
                            // logic.moments.refresh();
                            logic.discoverProductFlow(dynamicId: res);
                            logic.discoverFollowingDynamicList();
                          }
                        }),
                        // Image.asset(Assets.discoverSearch, width: 28, height: 28).marginRight(16),
                      ],
                    ).paddingSymmetric(horizontal: 16),
                    SizedBox(height: 4),
                    TabBarView(children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Image.asset(Assets.discoverBanner1).marginOnly(top: 10, bottom: 15),
                          EasyRefresh(
                            onRefresh: () async {
                              await logic.discoverProductFlow(showLoading: false);
                            },
                            onLoad: () async {
                              await logic.discoverProductFlow(load: true, showLoading: false);
                            },
                            header: ClassicHeader(
                              showText: false,
                              iconDimension: 100,
                              succeededIcon: const LoadFinish(),
                              progressIndicatorSize: 15,
                              progressIndicatorStrokeWidth: 1.5,
                              iconTheme: IconThemeData(color: const Color(0xFF9299B1), size: 18),
                            ),
                            // footer :ClassicFooter(),
                            footer: const ClassicFooter(
                              showText: false,
                              // noMoreIcon: Text(
                              //   'THE END',
                              //   style: TextStyle(
                              //       fontSize: 10, color: Color(0xFFDFDFDF)),
                              // ),
                            ),
                            child: MasonryGridView.count(
                              crossAxisCount: 2,
                              mainAxisSpacing: 6,
                              crossAxisSpacing: 4,
                              shrinkWrap: true,
                              // physics: NeverScrollableScrollPhysics(),
                              itemCount: logic.moments.length,
                              itemBuilder: (context, index) {
                                var moment = logic.moments[index];
                                return Stack(
                                  children: [
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          children: [
                                            if (moment.cover != null)
                                              CachedNetworkImage(
                                                imageUrl: moment.cover!,
                                                fit: BoxFit.fitWidth,
                                              ).expanded(),
                                          ],
                                        ).maxHeight(220),
                                        Text(moment.titleStr).marginOnly(top: 4, left: 7, right: 7, bottom: 10),
                                        Row(
                                          children: [
                                            JR
                                                .img(moment.userHeadUrl, fit: BoxFit.cover, width: 18, height: 18)
                                                .roundedRect(90)
                                                .marginOnly(left: 7, right: 5),
                                            Text(moment.userNickname).fontSize(12).colorInt(0xffC1C1C1),
                                            Spacer(),
                                            Image.asset(moment.isLike ? Assets.discoverStar : Assets.discoverStarGrey,
                                                width: 15, height: 15),
                                            SizedBox(width: 1),
                                            Text(moment.likes.toString()).fontSize(12).colorInt(0xffC1C1C1),
                                            SizedBox(width: 12),
                                          ],
                                        ).marginBottom(7),
                                      ],
                                    ).backgroundColor(Colors.white).roundedRect(8).onClick(() async {
                                      if (moment.type == 1) {
                                        var res = await Get.to(() => PostDetailPage(id: moment.id),
                                            arguments: {"moment": moment});
                                      }
                                      if (moment.type == 2) {
                                        Get.to(() => PlayerPage(id: moment.id), arguments: {"moment": moment});
                                      }
                                    }),
                                    Visibility(
                                        visible: moment.type == 2,
                                        child: JR
                                            .img(Assets.discoverPlay, width: 18, height: 18)
                                            .positioned(top: 8, right: 8)),
                                  ],
                                );
                              },
                            ),
                          ).expanded(),
                        ],
                      ).paddingSymmetric(horizontal: 16),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 16),
                          Row(
                            children: [
                              SizedBox(width: 16),
                              ...logic.followingUsers.map(
                                (user) {
                                  return Column(
                                    children: [
                                      Stack(
                                        children: [
                                          JR
                                              .img(user.headPortraitsUrl ?? "",
                                                  fit: BoxFit.cover, width: 42, height: 42)
                                              .roundedRect(90)
                                              .onClick(
                                                  () => Get.to(() => UserDetailsPage(userId: user.userId.toString())))
                                              .marginBottom(2),
                                          Visibility(
                                            visible: user.roomInfo != null,
                                            child: Center(
                                                    child: Text(T.current.join)
                                                        .fontSize(10)
                                                        .color(Colors.white)
                                                        .paddingSymmetric(horizontal: 7, vertical: 1)
                                                        .backgroundColorInt(0xff8A72FE)
                                                        .roundedRect(16))
                                                .positioned(bottom: 0, right: 0, left: 0),
                                          ),
                                        ],
                                      ),
                                      Text(user.nickname ?? "").fontSize(10).singleLine().maxWidth(68),
                                    ],
                                  ).marginRight(10);
                                },
                              ),
                            ],
                          ).scrollable(direction: Axis.horizontal).marginBottom(8),
                          Visibility(
                            visible: logic.followingUsers.isEmpty && logic.followMoments.isEmpty,
                            child: Center(
                              child: Image.asset(
                                Images.bgPlaceEmpty,
                                width: 200,
                                height: 200,
                              ).marginTop(100),
                            ),
                          ),
                          EasyRefresh(
                            onRefresh: () async {
                              await logic.discoverFollowingDynamicList(showLoading: false);
                              await logic.followList(showLoading: false);
                            },
                            onLoad: () async {
                              await logic.discoverFollowingDynamicList(load: true, showLoading: false);
                            },
                            header: ClassicHeader(
                              showText: false,
                              iconDimension: 100,
                              succeededIcon: const LoadFinish(),
                              progressIndicatorSize: 15,
                              progressIndicatorStrokeWidth: 1.5,
                              iconTheme: IconThemeData(color: const Color(0xFF9299B1), size: 18),
                            ),
                            footer: const ClassicFooter(
                              showText: false,
                              noMoreIcon: Text(
                                'THE END',
                                style: TextStyle(fontSize: 10, color: Color(0xFFDFDFDF)),
                              ),
                            ),
                            child: MasonryGridView.count(
                              crossAxisCount: 2,
                              mainAxisSpacing: 6,
                              crossAxisSpacing: 4,
                              itemCount: logic.followMoments.length,
                              itemBuilder: (context, index) {
                                var moment = logic.followMoments[index];
                                return Stack(
                                  children: [
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          children: [
                                            if (moment.cover != null)
                                              CachedNetworkImage(
                                                imageUrl: moment.cover!,
                                                fit: BoxFit.fitWidth,
                                              ).expanded(),
                                          ],
                                        ).maxHeight(220),
                                        Text(moment.titleStr).marginOnly(top: 4, left: 7, right: 7, bottom: 10),
                                        Row(
                                          children: [
                                            JR
                                                .img(moment.userHeadUrl, fit: BoxFit.cover, width: 18, height: 18)
                                                .roundedRect(90),
                                            SizedBox(width: 5),
                                            Text(moment.userNickname).fontSize(12).colorInt(0xffC1C1C1),
                                            Spacer(),
                                            Image.asset(moment.isLike ? Assets.discoverStar : Assets.discoverStarGrey,
                                                    width: 15, height: 15)
                                                .marginRight(1),
                                            Text(moment.likes.toString())
                                                .fontSize(12)
                                                .colorInt(0xffC1C1C1)
                                                .marginRight(12),
                                          ],
                                        ).marginBottom(7),
                                      ],
                                    ).backgroundColor(Colors.white).roundedRect(8).onClick(() {
                                      if (moment.type == 1) {
                                        Get.to(() => PostDetailPage(id: moment.id), arguments: {"moment": moment});
                                      }
                                      if (moment.type == 2) {
                                        Get.to(() => PlayerPage(id: moment.id), arguments: {"moment": moment});
                                      }
                                    }),
                                    Visibility(
                                        visible: moment.type == 2,
                                        child: JR
                                            .img(Assets.discoverPlay, width: 18, height: 18)
                                            .positioned(top: 8, right: 8)),
                                  ],
                                );
                              },
                            ).paddingSymmetric(horizontal: 16),
                          ).expanded(),
                        ],
                      ),
                    ]).expanded(),
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    });
  }
}
